<template>
  <div id="hotTopicAddEdit">
    <el-dialog class="about-set" :title="preview ? '查看话题' : isAdd ? '创建话题' : '编辑话题'" :visible.sync="dialogData.isShow" width="900px" top="80px" :before-close="labelHandleClose">
      <div class="form-box">
        <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="75px" class="demo-ruleForm">
          
          <el-form-item label="推荐频道" prop="channel">
            <el-select v-model="ruleForm.channel" filterable placeholder="请选择" :disabled="preview">
              <el-option v-for="item in channelList" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="话题名称" prop="topicName">
            <el-input v-model.trim="ruleForm.topicName" maxlength="30" show-word-limit clearable :disabled="preview"></el-input>
          </el-form-item>

          <el-form-item label="话题说明" prop="describes" style="margin-top:10px;">
            <el-input v-model.trim="ruleForm.describes" type="textarea" show-word-limit maxlength="50" clearable :disabled="preview"></el-input>
          </el-form-item>

          <el-form-item label="所属圈子">
            <el-select v-model="ruleForm.associatedCircles[0].circleId" filterable placeholder="请选择" :disabled="preview">
              <el-option v-for="item in circleList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="话题状态" prop="enabled">
            <el-radio-group v-model="ruleForm.enabled">
              <el-radio v-for="item in enabledList" :key="item.dictValue" :label="item.dictValue" :disabled="preview">
                {{ item.dictLabel }}
              </el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="话题头图" prop="icon">
            <uploadSingImg
              :imgUrl="ruleForm.icon"
              accept=".jpg,.jpeg,.png"
              :maxSize="2"
              :disabled="preview"
              @getImgUrl="getImgIcon"
            >
              <template v-slot:imgInfo>（限制上传2M以内）</template>
            </uploadSingImg>
          </el-form-item>

        </el-form>

        <h3 class="list-title">添加标签</h3>

        <el-form ref="formInline" :inline="true" :model="formInline" :rules="rulesInline" class="demo-form-inline">
          <el-form-item label="分类属性" prop="classifiAttr">
            <el-select v-model="formInline.classifiAttr" filterable placeholder="请选择" value-key="dictValue" :disabled="preview">
              <el-option v-for="item in classifiAttrList" :key="item.dictValue" :label="item.dictLabel" :value="item"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="选择分类" prop="classifiName">
            <el-select v-model="formInline.classifiName" filterable placeholder="请选择" value-key="id" :disabled="preview">
              <el-option v-for="item in classifiNameList" :key="item.id" :label="item.labelCategoryName" :value="item"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="选择标签名称" prop="labelName">
            <el-select v-model="formInline.labelName" filterable placeholder="请选择" value-key="id" :disabled="preview">
              <el-option v-for="item in labelNameList" :key="item.id" :label="`${item.labelName}-${item.id}`" :value="item">
                {{ item.labelName }}-{{ item.id }}
              </el-option>
            </el-select>
          </el-form-item>

          <el-button class="button" type="success" @click="handAdd" :disabled="preview">
            添加
          </el-button>
        </el-form>

        <!-- 表格部分 -->
        <el-table :data="tableData" style="width: 100%" height="320">
          <el-table-column type="index" width="60" align="center" label="序号"></el-table-column>
          <el-table-column label="分类属性" prop="tagAttr" width="110"></el-table-column>
          <el-table-column label="分类名" prop="tagCategoryName" width="160"></el-table-column>

          <el-table-column label="标签名+ID" prop="labelName" min-width="150">
            <template slot-scope="{ row }">
              {{ row.labelName }}-{{ row.id }}
            </template>
          </el-table-column>

          <el-table-column label="操作" width="100">
            <template slot-scope="scope">
              <el-button type="text" @click="delLine(scope.$index)" :disabled="preview">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button type="success" plain @click="cancelLabel">取 消</el-button>
        <el-button type="success" :loading="loading" @click="confirmLabel('ruleForm')" :disabled="preview">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { sysNormalDisable } from '@utils/dictionariesFunc'
import { add, edit } from '@/api/contentTags/hotTopic' // 接口
import { getCirclesOptions } from '@/api/circle/circleManage' // 接口
import { getClasses, getLabels } from '@/api/contentTags/configureTag' // 接口
import uploadSingImg from '@common/uploadSingImg' // 上传单个图片公共组件

export default {
  name: 'hotTopicAddEdit',
  msg: '热门话题推荐-新增/编辑弹窗',
  props: ['dialogData'],
  components: { uploadSingImg },
  data() {
    return {
      loading: false,
      isAdd: true, //是否新增
      preview: false, // 是否预览
      attrList: {}, //属性对象
      channelList: [], // 频道推荐列表
      enabledList: [],
      circleList: [], // 所属圈子
      classifiAttrList: [], //分类属性
      classifiNameList: [], //选择分类
      labelNameList: [], //标签名称
      defaultClassifiAttr: {
        //默认值
        dictLabel: '-- 请选择分类属性 --',
        dictValue: ''
      },
      defaultClassifiName: {
        //默认值
        labelCategoryName: '-- 请选择标签分类 --',
        id: ''
      },
      defaultLabelName: {
        //默认值
        labelName: '-- 请选择标签名 --',
        id: ''
      },
      ruleForm: {
        channel: null, // 推荐频道
        topicName: '', //话题名称
        enabled: null, // 话题状态
        describes: '', // 话题描述
        associatedCircles: [{
          circleId: '',
          circleType: 'INTEREST_CIRCLE'
        }], // 所属圈子
        icon: '', // 圈子头图
      },
      formInline: {
        classifiAttr: {}, //分类属性
        classifiName: {}, //选择分类
        labelName: {} //标签名称
      },
      rules: {
        channel: {
          required: false,
          message: '请选择推荐频道',
          trigger: 'blur'
        },
        topicName: {
          required: true,
          message: '请输入话题名称',
          trigger: 'blur'
        },
        enabled: {
          required: true,
          message: '请选择话题状态',
          trigger: 'blur'
        },
        describes: {
          required: false,
          message: '请输入话题描述',
          trigger: 'blur'
        },
        icon: {
          required: true,
          message: '请选择圈子头图',
          trigger: 'change'
        }
      },
      rulesInline: {},
      tableData: []
    }
  },
  watch: {
    'formInline.classifiAttr': {
      //分类属性
      handler(newVal, oldVal) {
        if (newVal) {
          this.setDefault()
          this.getClassList(newVal.dictValue)
        }
      },
      deep: true
    },
    'formInline.classifiName': {
      //标签分类
      handler(newVal, oldVal) {
        this.labelNameList = [this.defaultLabelName]
        this.formInline.labelName = this.defaultLabelName
        if (newVal.id) {
          //标签名
          this.getNameList(newVal.id)
        }
      },
      deep: true
    }
  },
  mounted() {
    this.isAdd = this.dialogData.id ? false : true
    this.preview = this.dialogData.type
    this.getStateList()
    this.setDefault()
  },
  methods: {
    async getStateList() {
      // 频道
      let data = await sysNormalDisable('sys_topic_channel')
      this.channelList = this.channelList.concat(data)
      // 话题状态
      let data2 = await sysNormalDisable('sys_labels_statu')
      this.enabledList = this.enabledList.concat(data2)
      // 分类属性
      let data3 = await sysNormalDisable('sys_labels_attribute')
      this.classifiAttrList = this.classifiAttrList.concat(data3)
      this.formInline.classifiAttr = this.classifiAttrList[0]
      data3.forEach((item) => {
        this.attrList[item.dictValue] = item.dictLabel
      })
      await getCirclesOptions((res) => {
        this.circleList = this.circleList.concat(res)
      })
      //获取标签分类列表
      this.getClassList(this.formInline.classifiAttr.dictValue)
      if (this.isAdd) {
        //新增
        // this.ruleForm.channel = this.channelList[0].dictValue
        this.ruleForm.enabled = this.enabledList[0].dictValue
      } else {
        //编辑
        this.getFormData()
      }
    },
    /*编辑-获取表单详情*/
    getFormData() {
      // debugger
      let obj = JSON.parse(JSON.stringify(this.dialogData.row))
      let { channel, topicName, enabled, describes, icon, circleIds } = obj
      this.ruleForm = {
        icon,
        channel,
        describes,
        topicName,
        associatedCircles: [{
          circleId: circleIds.length ? circleIds[0] : '',
          circleType: 'INTEREST_CIRCLE'
        }], // 所属圈子
        enabled: enabled.toString()
      }

      //获取table数据
      let ary = obj.contentLabelResourceList
      ary.forEach((item) => {
        let obj = {
          tagAttr: this.attrList[item.contentLabelCategory.labelCategoryProperty], //分类属性
          tagCategoryName: item.contentLabelCategory.labelCategoryName, //分类名
          labelName: item.labelName, //标签名称
          id: item.id //标签id
        }
        this.tableData.push(obj)
      })
    },
    /*设置默认值*/
    setDefault() {
      //标签分类
      this.classifiNameList = [this.defaultClassifiName]
      this.formInline.classifiName = this.defaultClassifiName
      //标签名
      this.labelNameList = [this.defaultLabelName]
      this.formInline.labelName = this.defaultLabelName
    },
    /*获取选择分类列表*/
    getClassList(id) {
      let obj = {
        labelCategoryProperty: id
      }
      getClasses(
        obj,
        (response) => {
          this.classifiNameList = [this.defaultClassifiName, ...response]
        },
        (response) => {
          this.$message.warning(response.message)
        }
      )
    },
    /*获取标签名称列表*/
    getNameList(id) {
      let obj = {
        isRecommend: true
      }
      getLabels(
        id,
        obj,
        (response) => {
          this.labelNameList = [this.defaultLabelName, ...response]
        },
        (response) => {
          this.$message.warning(response.message)
        }
      )
    },
    /*选中标签添加到 table 中*/
    handAdd() {
      if (this.tableData.length >= 50) {
        this.$message.warning('一个话题只能关联50个标签')
        return
      }
      if (!this.formInline.labelName || !this.formInline.labelName.id) {
        return
      }
      let curTags = this.formInline.labelName
      let i = this.tableData.findIndex(
        (item) => item.id.toString() === curTags.id
      )
      //数据重复，不允许加入this.tableData
      if (i >= 0) {
        this.$message.warning('该数据已存在列表中!')
        return
      }
      let curObj = { ...this.formInline }
      let obj = {
        tagAttr: curObj.classifiAttr.dictLabel, //分类属性
        tagCategoryName: curObj.classifiName.labelCategoryName, //分类名
        labelName: curObj.labelName.labelName, //标签名称
        id: curObj.labelName.id //标签id
      }
      this.tableData.push(obj)
    },
    /*删除*/
    delLine(i) {
      this.$confirm('确定移除标签吗？', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.tableData.splice(i, 1)
        })
        .catch(() => {})
    },
    labelHandleClose(done) {
      this.cancelLabel()
      done()
    },
    cancelLabel() {
      // 关闭前清空
      this.loading = false
      this.dialogData.id = ''
      this.dialogData.row = {}
      this.dialogData.isShow = false
    },
    getLabelIds() {
      let ary = this.tableData
      let ids = []
      ary.forEach((item) => {
        ids.push(item.id)
      })
      return ids
    },
    /* 确认提交 */
    confirmLabel(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let labelIds = this.getLabelIds()
          // if (labelIds.length === 0) {
          //   this.$message.warning('请添加标签！')
          //   return
          // }
          this.loading = true
          let obj = { ...this.ruleForm, labelIds }
          obj.enabled = obj.enabled === 'true' ? true: false

          if (this.isAdd) {
            //新增
            add(obj, (response) => {
              this.$emit('refresh')
              this.cancelLabel()
            },(response) => {
              this.$message.warning(response.message)
              this.loading = false
            })
          } else {
            //编辑
            edit(this.dialogData.id, obj, (response) => {
              this.$message.success('操作成功')
              this.$emit('refresh')
              this.cancelLabel()
            },(response) => {
              this.$message.warning(response.message)
              this.loading = false
            })
          }
        } else {
          return false
        }
      })
    },
     //圈子头图设置
    getImgIcon(url) {
      this.ruleForm.icon = url
      this.$refs['ruleForm'].clearValidate(['icon'])
    }
  }
}
</script>

<style lang="less">
#hotTopicAddEdit {
  .list-title {
    font-size: 15px;
    color: #333;
    font-weight: bold;
    line-height: 20px;
    padding-bottom: 10px;
    margin: 12px 0;
    border-bottom: 1px solid #eee;
  }
  .demo-form-inline {
    .el-form-item__content {
      width: 184px;
    }
    .el-button {
      margin-top: 6px;
    }
  }
  .el-table {
    margin-bottom: 20px;
  }
}
</style>
